package cn.conac.as.push.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.conac.as.push.entity.AndroidBroadcast;
import cn.conac.as.push.entity.AndroidNotification;
import cn.conac.as.push.entity.AndroidUnicast;
import cn.conac.as.push.entity.Broadcast;
import cn.conac.as.push.entity.Extra;
import cn.conac.as.push.entity.IOSBroadcast;
import cn.conac.as.push.entity.IOSUnicast;
import cn.conac.as.push.entity.PushClient;
import cn.conac.as.push.entity.User;

@Controller
public class PushController
{
	@Value("${push.appkeyAndroid}")
	private String appkeyAndroid;

	@Value("${push.appkeyIOS}")
	private String appkeyIOS;
	@Value("${push.appMasterSecretAndroid}")
	private String appMasterSecretAndroid;
	@Value("${push.appMasterSecretIOS}")
	private String appMasterSecretIOS;

	private String timestamp = null;
	private PushClient clientAndroid = new PushClient();
	private PushClient clientIOS = new PushClient();


	/**
	 * 控制台日志
	 */
	private Logger logger = Logger.getLogger(PushController.class.getName());



	public HttpResponse sendAndroidBroadcast(Broadcast broadcast) throws Exception {
		AndroidBroadcast broadcastAndroid = new AndroidBroadcast(appkeyAndroid,appMasterSecretAndroid);

        broadcastAndroid.setDescription(broadcast.getTitle());
        broadcastAndroid.setTitle(  broadcast.getTitle());
        broadcastAndroid.setText(  broadcast.getText());
        broadcastAndroid.setTicker(broadcast.getTitle());
        broadcastAndroid.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);

        // TODO Set 'production_mode' to 'false' if it's a test device.
        // For how to register a test device, please see the developer doc.
//		unicast.setProductionMode();
//		测试模式
        broadcastAndroid.setProductionMode();
        broadcastAndroid.setExpireTime(broadcast.getExpireTime());
        broadcastAndroid.setStartTime(broadcast.getStartTime());
        List<Extra> extraJson = broadcast.getExtraJson();
        if(extraJson!=null){
            for (Extra extra :extraJson){
                broadcastAndroid.setExtraField(extra.getExtraKey(),extra.getExtraValue());
            }
        }
        HttpResponse androidResponse = clientAndroid.send(broadcastAndroid);
        int status = androidResponse.getStatusLine().getStatusCode();
        logger.info("Android Response Code : " + status);
        BufferedReader rd = new BufferedReader(new InputStreamReader(androidResponse.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
		logger.info(result.toString());
        if (status == 200) {
            logger.info(" Android 发送成功");
        } else {
            logger.info("Android 发送失败!");
        }
        return androidResponse;

	}
	
	public HttpResponse sendAndroidUnicast(Broadcast broadcast) throws Exception {
		System.out.println("安卓单播+++++++++++++++++++++++++++++++++++++++");

		AndroidUnicast unicast = new AndroidUnicast(appkeyAndroid,appMasterSecretAndroid);
		// TODO Set your device token
		unicast.setDeviceToken( "AssE1JXkoT1pwgTt8-YE2mWfbDYXDDkJ8gYkj85PfyRY");
		unicast.setDescription(broadcast.getText());
		unicast.setTitle( broadcast.getTitle() );
		unicast.setText(  broadcast.getText());
		unicast.setTicker("111" );

		unicast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);

		// TODO Set 'production_mode' to 'false' if it's a test device. 
		// For how to register a test device, please see the developer doc.
//		unicast.setProductionMode();
//		测试模式
		unicast.setTestMode();
		unicast.setExpireTime(broadcast.getExpireTime());
		unicast.setStartTime(broadcast.getStartTime());
		List<Extra> extraJson = broadcast.getExtraJson();
		if(extraJson!=null){
			for (Extra extra :extraJson){
				unicast.setExtraField(extra.getExtraKey(),extra.getExtraValue());
			}
		}
		HttpResponse androidResponse = clientAndroid.send(unicast);
		int status = androidResponse.getStatusLine().getStatusCode();
		logger.info("Android Response Code : " + status);
		BufferedReader rd = new BufferedReader(new InputStreamReader(androidResponse.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		logger.info(result.toString());
		if (status == 200) {
			logger.info(" Android 发送成功");
		} else {
			logger.info("Android 发送失败!");
		}
		System.out.println("安卓单播完成+++++++++++++++++++++++++++++++++++++++");
		// Set customized fields
		return androidResponse;
	}


    public HttpResponse sendIOSBroadcast(Broadcast broadcast) throws Exception {
        IOSBroadcast broadcastIOS = new IOSBroadcast(appkeyIOS,appMasterSecretIOS);

        broadcastIOS.setAlert(broadcast.getText());
        broadcastIOS.setBadge(1);
        broadcastIOS.setDescription(broadcast.getTitle());

        broadcastIOS.setSound( "default");

        // TODO set 'production_mode' to 'true' if your app is under production mode
        broadcastIOS.setProductionMode();
        broadcastIOS.setExpireTime(broadcast.getExpireTime());
        broadcastIOS.setStartTime(broadcast.getStartTime());
        List<Extra> extraJson = broadcast.getExtraJson();
        // Set customized fields
        if(extraJson!=null){
            for (Extra extra :extraJson){
                broadcastIOS.setCustomizedField(extra.getExtraKey(),extra.getExtraValue());
            }
        }
        HttpResponse iosResponse = clientIOS.send(broadcastIOS);
        int status = iosResponse.getStatusLine().getStatusCode();
        logger.info("IOS Response Code : " + status);
        BufferedReader rd = new BufferedReader(new InputStreamReader(iosResponse.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
		logger.info(result.toString());
        if (status == 200) {
            logger.info("IOS 发送成功");
        } else {
            logger.info("IOS 发送失败");
        }
        return  iosResponse;

    }
	public HttpResponse sendIOSUnicast(Broadcast broadcast) throws Exception {
		System.out.println("IOS单播+++++++++++++++++++++++++++++++++++++++");
		IOSUnicast unicast = new IOSUnicast(appkeyIOS,appMasterSecretIOS);
		// TODO Set your device token
		unicast.setDeviceToken( "08dccb485cbe1841bfc254a5170f51fc26eb45663bb9cefe616fa911d9edc9c0");
		unicast.setAlert(broadcast.getTitle());
		unicast.setBadge( 0);
		unicast.setDescription(broadcast.getDescription());


		unicast.setSound( "default");
		unicast.setDescription("机构编制云消息推送");
		// TODO set 'production_mode' to 'true' if your app is under production mode
		unicast.setTestMode();
		unicast.setExpireTime(broadcast.getExpireTime());
		unicast.setStartTime(broadcast.getStartTime());
		List<Extra> extraJson = broadcast.getExtraJson();
		// Set customized fields
		if(extraJson!=null){
			for (Extra extra :extraJson){
				System.out.println("key:"+extra.getExtraKey()+"++++++value:"+extra.getExtraValue());
				unicast.setCustomizedField(extra.getExtraKey(),extra.getExtraValue());
			}
		}
		HttpResponse iosResponse = clientIOS.send(unicast);
		int status = iosResponse.getStatusLine().getStatusCode();
		logger.info("IOS Response Code : " + status);
		BufferedReader rd = new BufferedReader(new InputStreamReader(iosResponse.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		System.out.println(result.toString());
		if (status == 200) {
			logger.info("IOS 发送成功");
		} else {
			logger.info("IOS 发送失败");
		}
		System.out.println("ios单播+结束++++++++++++++++++++++++++++++++++++++");
		return  iosResponse;
	}

	@RequestMapping("/bdtlaw/messagesp/index")
	public String helloHtml(Map<String,Object> map,HttpSession session){
		String username = (String)session.getAttribute("username");
		String password = (String)session.getAttribute("password");
		if(username==null || password == null){
			return "home";
		}
		if (!"Xjsy@2017=Gtfz".equals(password) || !username.equals("中央编办事业发展中心")){
			return "home";
		}
		return "push";
	}

	@RequestMapping("/bdtlaw/messagesp/index/home")
	public String home(Model model){
		return "home";
	}

	@RequestMapping("/bdtlaw/messagesp/index/logout")
	public String logout(Model model,HttpSession session){
		session.setAttribute("username",null);
		session.setAttribute("password",null);
		return "home";
	}


	@RequestMapping(value = "/bdtlaw/messagesp/index/login",method = RequestMethod.POST)
	public ResponseEntity<Object> pushIndex(@RequestBody User user,HttpSession session){
		Map<String, Object> map = new HashMap<>();
		String password = user.getPassword();
		String username = user.getUsername();
		if (!"Xjsy@2017=Gtfz".equals(password) || !username.equals("中央编办事业发展中心")){
			map.put("message", "密码错误");
			map.put("status", 400);
			ResponseEntity<Object> response = new ResponseEntity<Object>(map,HttpStatus.OK);
			return response;
		}
		session.setAttribute("username",username);
		session.setAttribute("password",password);
		map.put("status", 200);
		ResponseEntity<Object> response = new ResponseEntity<Object>(map, HttpStatus.OK);
		return response;
	}

	@RequestMapping(value = "/bdtlaw/messagesp/index/push",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<Object> vueHtml (@RequestBody Broadcast broadcast){
		 Map<String, Object> map = new HashMap<String, Object>();

		try {
			System.out.println("单---播开始+++++++++++++++++++++++++++++++++++++++");
            //测试单播
			HttpResponse androidResponse = this.sendAndroidUnicast(broadcast);
            //正式广播
//			HttpResponse androidResponse = this.sendAndroidBroadcast(broadcast);
			int androidStatus = androidResponse.getStatusLine().getStatusCode();
			System.out.println("安卓-------------------------单---播+++++++++++++++++++++++++++++++++++++++");
			EntityUtils.consumeQuietly(androidResponse.getEntity());
            //测试单播
			HttpResponse iosResponse = this.sendIOSUnicast(broadcast);
            //正式广播
//			HttpResponse iosResponse = this.sendIOSBroadcast(broadcast);
			int iosStatus = iosResponse.getStatusLine().getStatusCode();
			EntityUtils.consumeQuietly(iosResponse.getEntity());
			System.out.println("播+完了++++++++++++++++++++++++++++++++++++++");
			map.put("androidStatus",androidStatus );
			map.put("iosStatus", iosStatus);

			if(androidStatus==200 && iosStatus ==200){
				map.put("status", 200);
				ResponseEntity<Object> response = new ResponseEntity<Object>(map, HttpStatus.OK);
				return response;
			}else{
				map.put("status", 400);
				ResponseEntity<Object> response = new ResponseEntity<Object>(map, HttpStatus.BAD_REQUEST);
				return response;
			}

		}catch (Exception ex) {
			ex.printStackTrace();
			map.put("status", 400);
			return new ResponseEntity<Object>(map, HttpStatus.OK);
		}
	}



}


